// pages/order-confirm/order-confirm.js
const app = getApp()
const equipmentTypeMap = {
  medical_imaging: { text: '医疗影像', color: '#2196f3' },
  surgical: { text: '手术器械', color: '#e91e63' },
  rehabilitation: { text: '康复设备', color: '#afb42b' },
  other: { text: '其他设备', color: '#afb42b' }
};
Page({
  data: {
    equipment: null,
	equipmentId:'',
    type: '', // 类型：rent-租赁 sale-售卖
    form: {
      days: '',
	  saletype:'rent',
      contactName: '',
      contactPhone: '',
      address: ''
    },
    calculate: {
      rentFee: 0,
      total: 0
    },
    formValid: false
  },

  onLoad(options) {
	  this.equipmentId = options.equipmentId
	  console.log(options.equipmentId)
	  this.setData({
	    equipmentId: options.equipmentId,
	    type: options.type || 'rent'
	  });
    this.loadEquipmentData(options.equipmentId)
  },

  // 加载设备数据
  loadEquipmentData(id) {
    // 模拟数据，实际应从接口获取
	var that = this
	app.util.request({
	        url: 'Qxzl/detail',
	        data: {
						   id:id
	        },
	        success(res) {
	                var data = res.data.data;
	     					  console.log(data)
	                 that.setData({
	                        equipment: {
	                          ...data.shebei,
	                          typeText: equipmentTypeMap[data.type]?.text || '其他设备',
	                          typeColor: equipmentTypeMap[data.type]?.color || '#666'
	                        },
	                        loading: false
	                      });
					const total = Number(data.shebei.saleprice)
					that.setData({
					  calculate: {
						total: total.toFixed(2)
					  }
					}, that.checkForm)
	        }
	})
  },

  // 表单输入处理
  onDaysChange(e) {
    this.setData({ 'form.days': e.detail.value }, this.calculatePrice)
  },
  onNameChange(e) {
    this.setData({ 'form.contactName': e.detail.value }, this.checkForm)
  },
  onPhoneChange(e) {
    this.setData({ 'form.contactPhone': e.detail.value }, this.checkForm)
  },
  onAddressChange(e) {
    this.setData({ 'form.address': e.detail.value }, this.checkForm)
  },

  // 计算价格
  calculatePrice() {
	if(this.data.type == 'rent'){
		const days = Number(this.data.form.days)
		const rentFee = days * this.data.equipment.price
		const total = Number(rentFee) + Number(this.data.equipment.yajin)
		console.log(rentFee)
		console.log(this.data.equipment.yajin)
		this.setData({
		  calculate: {
			rentFee: rentFee.toFixed(2),
			total: total.toFixed(2)
		  }
		}, this.checkForm)
	}else{
		const total = Number(this.data.equipment.saleprice)
		this.setData({
		  calculate: {
			total: total.toFixed(2)
		  }
		}, this.checkForm)
	}
  },

  // 表单验证
  checkForm() {
    let valid = this.data.form.contactName.trim() &&
                 /^1[3-9]\d{9}$/.test(this.data.form.contactPhone) &&
                 this.data.form.address.trim()
    if(this.data.type == 'rent'){
		valid = this.data.form.days > 0 && valid
	}
    this.setData({ formValid: valid })
  },

  // 提交订单
  handleSubmit() {
	  console.log(this.data.formValid)
	  var that = this
    if (!this.data.formValid) return

    try {
      // 检查认证状态
      // const isAuth = await this.checkAuth()
      // if (!isAuth) return
	this.data.form.saletype = this.data.type
      // 序列化提交数据对象
      var form = encodeURI(JSON.stringify(this.data.form));
	  console.log(form)
	  app.util.request({
	          url: 'Order/shebei',
	          data: {
	              form: form,
				  equipmentId:this.equipmentId,
				  calculate:encodeURI(JSON.stringify(this.data.calculate))
	          },
	          success(res) {
	              var order_id=res.data.data.order_id;
	              var pay_params=res.data.data.pay_params;
	  
	              wx.requestPayment({
	                  'timeStamp': pay_params.timeStamp,
	                  'nonceStr': pay_params.nonceStr,
	                  'package': pay_params.package,
	                  'signType': 'MD5',
	                  'paySign': pay_params.paySign,
	                  'success': function (resp) {
	                         wx.navigateTo({
	                           url: `/vp_pz/pages/order/index`
	                         });
	                  },
	                  'fail': function (res) {
	                        wx.showToast({ title: '支付失败', icon: 'none' })
	                  }
	              })
	          }
	  })
    } catch (error) {
      wx.showToast({ title: '提交失败', icon: 'none' })
    }
  },

  // 检查认证
  async checkAuth() {
    if (!app.globalData.userInfo?.isCertified) {
      const res = await wx.showModal({
        title: '需要认证',
        content: '请先完成实名认证',
        confirmText: '去认证'
      })
      if (res.confirm) {
        wx.navigateTo({ url: '/pages/user/auth' })
      }
      return false
    }
    return true
  }
})